import { useState, useEffect, useRef } from "react";
import {
  Table,
  Select,
  DatePicker,
  Button,
  Row,
  Col,
  message,
  Space,
  Pagination,
  Radio,
} from "antd";
import type { TableProps } from "antd";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";
import dataMgrService from "@/api/datamgr/datamgr";
import deviceService from "@/api/device/device";
// import type { TableName, HistoryDataItem, HistoryQueryParams } from "#/datamgr";
import "../style/index.css";
import { tableDemoData } from "./demo";
const { RangePicker } = DatePicker;

interface TableHeader {
  showCode: string;
  showName: string;
  orderNum: number;
}

function HistoryData() {
  // 状态定义
  const [listQuery, setListQuery] = useState<any>({
    pageNo: 1,
    pageSize: 10,
    type: 0,
    sectionId: undefined,
    sectionName: undefined,
    deviceId: undefined,
  });

  const [queryType, setQueryType] = useState(0);
  const [deviceValue, setDeviceValue] = useState<string>();
  const [rangeDate, setRangeDate] = useState<[Dayjs, Dayjs]>();
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [secList, setSecList] = useState<any[]>([]);
  const [tableHeaderList, setTableHeaderList] = useState<any[]>([]);
  const [lineData, setLineData] = useState<EChartsOption>();

  // echarts 相关
  const lineChartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts>();

  // 日期快捷选项
  const dateShortcuts = {
    items: [
      {
        label: '最近一周',
        value: [dayjs().subtract(7, 'day'), dayjs()]
      },
      {
        label: '最近一个月',
        value: [dayjs().subtract(30, 'day'), dayjs()]
      },
      {
        label: '最近三个月',
        value: [dayjs().subtract(90, 'day'), dayjs()]
      }
    ]
  };

  // 初始化
  useEffect(() => {
    init();
    return () => {
      chartInstance.current?.dispose();
    };
  }, []);

  // 图表更新
  useEffect(() => {
    if (lineData && lineChartRef.current) {
      if (!chartInstance.current) {
        chartInstance.current = echarts.init(lineChartRef.current);
      }
      chartInstance.current.setOption(lineData);
    }
  }, [lineData]);

  // 窗口大小变化时重绘图表
  useEffect(() => {
    const handleResize = () => {
      chartInstance.current?.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      chartInstance.current?.dispose();
    };
  }, []);

  const init = async () => {
    await fetchSectionListData();
  };

  // 获取断面列表
  const fetchSectionListData = async () => {
    try {
      setLoading(true);
      const response = await deviceService.getDeviceList({ type: queryType });
      if (response?.data) {
        setSecList(response.data);
        if (response.data.length > 0) {
          const firstDevice = response.data[0];
          setDeviceValue(firstDevice.deviceId);
          setListQuery((prev) => ({
            ...prev,
            deviceId: firstDevice.deviceId,
            sectionId: firstDevice.sectionId,
            sectionName: firstDevice.sectionName,
          }));
        }
      }
    } catch (err) {
      console.error("Error fetching section list:", err);
    } finally {
      setLoading(false);
    }
  };

  // 处理断面选择变化
  const handleDeviceChange = (value: string) => {
    const selectedDevice = secList.find((item) => item.deviceId === value);
    if (selectedDevice) {
      setDeviceValue(value);
      setListQuery((prev) => ({
        ...prev,
        deviceId: value,
        sectionId: selectedDevice.sectionId,
        sectionName: selectedDevice.sectionName,
      }));
    }
  };

  // 格式化单元格数据
  const formatCellValue = (value: any) => {
    if (value === null || value === undefined) {
      return "-";
    }
    if (typeof value === "object") {
      // 如果是对象，返回特定字段或转为字符串
      return value.value || value.toString() || "-";
    }
    return value;
  };

  // 表格列配置
  const columns = tableHeaderList.map((item) => ({
    title: item.label,
    dataIndex: item.prop,
    key: item.prop,
    fixed: item.fixed,
    width: item.width,
    ellipsis: true,
    render: (value: any) => <span>{formatCellValue(value)}</span>,
  }));

  // 处理后端返回的数据
  const processTableData = (data: any[]) => {
    return data.map((row, index) => {
      const processedRow: any = {
        // 添加一个唯一的 key
        _key: `${row.time || row.collectionDate || index}`,
        ...row,
      };
      // 处理每个字段的值
      for (const key in processedRow) {
        if (key !== "_key") {
          // 跳过 key 字段的处理
          processedRow[key] = formatCellValue(processedRow[key]);
        }
      }
      return processedRow;
    });
  };

  // 获取历史数据列表
  const fetchDataHistoryList = async (
    page: number = 1,
    pageSize: number = 10
  ) => {
    if (!checkQuery()) return;

    try {
      setLoading(true);
      const params = {
        ...listQuery,
        pageNo: page,
        pageSize,
        startTime: rangeDate?.[0].format("YYYY-MM-DD HH:mm:ss"),
        endTime: rangeDate?.[1].format("YYYY-MM-DD HH:mm:ss"),
        type: queryType,
      };

      const response = await dataMgrService.getDataSectionHistorylist(params);
      if (response?.data) {
        // 处理表头
        const headers = response.data.tableNames.map((item: any) => ({
          prop: item.showCode,
          label: item.showName,
          fixed: item.showName === "时间" ? "left" : undefined,
          width: item.showName === "时间" ? 158 : undefined,
        }));

        setTableHeaderList(headers);

        // 处理表格数据
        if (response.data.pageList) {
          const processedData = processTableData(
            response.data.pageList.list || []
          );
          setList(processedData);
          setTotal(response.data.pageList.count || 0);
        } else {
          setList([]);
          setTotal(0);
        }
      }
    } catch (err) {
      console.error("Error fetching history data:", err);
      message.error("获取数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取图表数据
  const fetchChartData = async () => {
    try {
      setLoading(true);
      const params = {
        ...listQuery,
        startTime: rangeDate?.[0].format("YYYY-MM-DD HH:mm:ss"),
        endTime: rangeDate?.[1].format("YYYY-MM-DD HH:mm:ss"),
        type: queryType,
      };

      const response = await dataMgrService.getHistoryDataSectionLinelist(params);
      if (response?.data) {
        const listLineData = response.data;
        if (listLineData && listLineData.length > 0) {
          // 处理图例和系列数据
          const legendList = [];
          const seriesData = [];
          const legendSelected = {};

          // 遍历数据处理图例和系列
          for (let i = 0; i < listLineData.length; i++) {
            const item = listLineData[i];
            legendList.push(item.name);
            
            // 设置图例选中状态
            legendSelected[item.name] = true;

            // 构建系列数据
            const seriesInfo = {
              name: item.name,
              type: 'line',
              smooth: true,
              symbol: 'none',
              data: item.value
            };
            seriesData.push(seriesInfo);
          }

          // 构建图表配置
          const chartOption: EChartsOption = {
            tooltip: {
              trigger: 'axis',
              formatter: function (params: any[]) {
                if (!params) return '';
                
                // 获取时间
                const time = params[0].axisValue;
                
                // 构建提示内容
                let html = `${time}<br/>`;
                
                // 添加每个系列的数据
                params.forEach(param => {
                  const value = param.value === undefined ? '-' : param.value;
                  html += `${param.marker}${param.seriesName}: ${value}<br/>`;
                });
                
                return html;
              },
              axisPointer: {
                type: 'cross',
                label: {
                  backgroundColor: '#6a7985'
                }
              }
            },
            legend: {
              data: legendList,
              selected: legendSelected,
              top: 30
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: listLineData[0].timeList  // 使用第一个数据项的时间列表
            },
            yAxis: {
              type: 'value'
            },
            series: seriesData
          };

          setLineData(chartOption);

          // 确保图表实例存在并更新
          if (lineChartRef.current) {
            if (!chartInstance.current) {
              chartInstance.current = echarts.init(lineChartRef.current);
            }
            chartInstance.current.setOption(chartOption);
          }
        }
      } else {
        setLineData(undefined);
        chartInstance.current?.dispose();
      }
    } catch (err) {
      console.error("Error fetching chart data:", err);
      message.error("获取图表数据失败");
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = async () => {
    if (!checkQuery()) return;

    try {
      setLoading(true);
      const params = {
        ...listQuery,
        startTime: rangeDate?.[0].format("YYYY-MM-DD HH:mm:ss"),
        endTime: rangeDate?.[1].format("YYYY-MM-DD HH:mm:ss"),
        deviceId: deviceValue,
        type: queryType,
      };

      const response = await dataMgrService.exportDataSectionHistorylist(
        params
      );
      if (response) {
        const blob = new Blob([response], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `历史数据_${dayjs().format(
          "YYYY-MM-DD_HH-mm-ss"
        )}.xlsx`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      }
    } catch (err) {
      console.error("Error exporting data:", err);
    } finally {
      setLoading(false);
    }
  };

  // 查询条件检查
  const checkQuery = () => {
    if (!deviceValue) {
      message.warning("请选择断面");
      return false;
    }
    if (!rangeDate) {
      message.warning("请选择日期");
      return false;
    }
    return true;
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize: number) => {
    setListQuery(prev => ({
      ...prev,
      pageNo: page,
      pageSize: pageSize
    }));
    fetchDataHistoryList(page, pageSize);
  };

  // 处理每页条数变化
  const handleSizeChange = (current: number, size: number) => {
    setListQuery(prev => ({
      ...prev,
      pageNo: 1,  // 切换每页条数时重置为第一页
      pageSize: size
    }));
    fetchDataHistoryList(1, size);
  };

  // 处理查询类型变化
  const handleQueryTypeChange = (value: number) => {
    setQueryType(value);
    setListQuery((prev) => ({
      ...prev,
      type: value,
    }));
  };

  // 在查询时同时获取表格和图表数据
  const handleSearch = () => {
    fetchDataHistoryList();
    fetchChartData();
  };

  return (
    // 最外层容器，占满整个页面高度
    <div className="h-full flex flex-col">
      {/* 固定在顶部的搜索区域 */}
      <div className="p-6 pb-4 flex-none bg-white">
        <Row gutter={[16, 16]} align="middle">
          <Col flex="320px">
            <div className="flex items-center">
              <label className="inline-block w-20 text-right mr-2">
                断面名称
              </label>
              <Select
                value={deviceValue}
                placeholder="请选择断面"
                onChange={handleDeviceChange}
                className="w-full"
                allowClear
                showSearch
                options={secList.map((item) => ({
                  value: item.deviceId,
                  label: item.sectionName,
                }))}
                filterOption={(input, option) =>
                  (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
                }
              />
            </div>
          </Col>

          <Col>
            <Radio.Group
              value={queryType}
              onChange={(e) => handleQueryTypeChange(e.target.value)}
              className="ml-4"
            >
              <Radio.Button value={0}>点位</Radio.Button>
              <Radio.Button value={1}>流量计</Radio.Button>
            </Radio.Group>
          </Col>

          <Col flex="420px">
            <div className="flex items-center">
              <label className="inline-block w-20 text-right mr-2">
                时间范围
              </label>
              <RangePicker
                showTime
                value={rangeDate}
                onChange={(dates) => setRangeDate(dates as [Dayjs, Dayjs])}
                className="w-full"
                presets={dateShortcuts.items}
              />
            </div>
          </Col>

          <Col flex="auto" className="text-right">
            <Space>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
              <Button onClick={handleExport}>导出</Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 可滚动的内容区域 */}
      <div className="flex-1 overflow-auto p-6 pt-0">
        {/* 表格区域 */}
        <div className="bg-white">
          <Table
            columns={columns}
            dataSource={list}
            loading={loading}
            pagination={false}
            scroll={{ 
              x: true,
            }}
            className="custom-table"
            size="small"
            bordered
            rowKey="_key"
          />

          <div className="py-3">
            <div className="flex justify-end">
              <Pagination
                total={total}
                current={listQuery.pageNo}
                pageSize={listQuery.pageSize}
                onChange={handlePageChange}
                onShowSizeChange={handleSizeChange}
                showSizeChanger
                showQuickJumper
                showTotal={(total) => `共 ${total} 条`}
                size="small"
                pageSizeOptions={['10', '20', '30', '50', '100']}
              />
            </div>
          </div>
        </div>

        {/* 图表区域 */}
        <div className="mt-4 bg-white p-4" style={{ height: "600px" }} ref={lineChartRef} />
      </div>
    </div>
  );
}

export default HistoryData;
